<div>
    <div>离考试结束还剩：<span id="countDown" style="color: red;font: bold;">120:00</span></div>
    
    <form class="layui-form" action="">
        <div class="layui-form-item">
          <label class="layui-form-label">试卷ID</label>
          <div class="layui-input-block">
            <input type="text" name="examId" id="examId" lay-verify="title" autocomplete="off" placeholder="请输入试卷ID" class="layui-input">
          </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
              <button type="submit" id="demo1" class="layui-btn" lay-submit="" lay-filter="demo1">开始考试</button>
              <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
          </div> 
    </form>
</div>
<script>
    layui.use(['element','jquery','form'], function(){
        var element = layui.element;
        var $ = layui.jquery;
        var upload = layui.upload;
        var form = layui.form;

         //监听提交
         form.on('submit(demo1)', function(data){
            openSocket($("#examId").val());

            return false;
         });

        var socket;
        function openSocket(examId) {
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else{
                console.log("您的浏览器支持WebSocket");

                var socketUrl="http://localhost:8080/exam/"+examId;
                socketUrl=socketUrl.replace("https","ws").replace("http","ws");
                console.log(socketUrl)
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function() {
                    console.log("websocket已打开");
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                //获得消息事件
                socket.onmessage = function(msg) {
                    console.log(msg.data);
                    $("#countDown").text(msg.data);
                };
                //关闭事件
                socket.onclose = function() {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function() {
                    console.log("websocket发生了错误");
                }
            }
        }
        function sendMessage() {
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else {
                console.log("您的浏览器支持WebSocket");
                socket.send('[{"msg":"您好"}]');
            }
        }
    });

   
</script>